package com.ysx.server.controller;

import com.ysx.server.pojo.dto.GoodsAddDTO;
import com.ysx.server.pojo.dto.SearchGoodsDTO;
import com.ysx.server.pojo.entity.Goods;
import com.ysx.server.pojo.vo.GoodsVO;
import com.ysx.server.recommend.service.RecommendService;
import com.ysx.server.service.GoodsService;
import com.ysx.server.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RecommendService recommendService;

    /**
     * 获取全部商品
     * @return
     */
    @GetMapping("getGoods")
    @Cacheable(cacheNames = "goodsCache_all")
    public Result<List<Goods>> getGoods(){
        List<Goods> goodsList=goodsService.getGoods();
        log.info("{} 查找商品：{}",goodsList);
        return Result.success(goodsList);
    }

    /**
     * 商品推荐
     * @param id
     * @return
     */
    @GetMapping("/recommend")
    public List<Goods> getRecommendGoods(Long id){
        log.info("{}获取推荐商品",id);
        if(id==null)
            return null;
        List<Goods> goods = recommendService.recommendGoods(id, 48);
        log.info("{} 获取推荐商品：{}",id,goods);
        return goods;
    }

    /**
     * 获取最新商品
     * @return
     */
    @GetMapping("/newGoods")
    @Cacheable(cacheNames = "goodsCache_new")
    public List<Goods> getNewGoods(){
        List<Goods> goods = goodsService.getNewGoods();
        log.info("获取最新商品：{}",goods);
        return goods;
    }

    /**
     * 搜索商品
     * @param searchGoodsDTO
     * @return
     */
    @PostMapping("/search")
    public List<Goods> search(@RequestBody SearchGoodsDTO searchGoodsDTO){
        log.info("搜索商品：{}",searchGoodsDTO);
        if(searchGoodsDTO==null)
            return null;
        List<Goods> goodsList=goodsService.getByName(searchGoodsDTO.getName());
        return goodsList;
    }

    /**
     * 商品详情
     * @param id 商品id
     * @return
     */
    @GetMapping("/details/{id}")
    @Cacheable(cacheNames = "goodsCache",key = "#id")
    public GoodsVO detail(@PathVariable Long id){
        log.info("查找商品：{}",id);
        if(id==null||id < 0)
            return null;
        GoodsVO goodsVO = goodsService.getById(id);
        log.info("查找商品：{}",goodsVO);
        return goodsVO;
    }

    /**
     * 新增商品
     * @param goodsAddDTO
     * @return
     */
    @PostMapping("/add")
    @CacheEvict(cacheNames = {"goodsCache_new","goodsCache_all","goodsCache"},allEntries=true)
    public boolean addGoods(@RequestBody GoodsAddDTO goodsAddDTO){
        log.info("新增商品：{}",goodsAddDTO);
        if(goodsAddDTO==null)
            return false;
        return goodsService.addGoodsAndCategory(goodsAddDTO);
    }
}
